package com.szz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.szz.domain.User;
import com.szz.mapper.UserMapper;
import com.szz.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/*
    Security的UserDetailsService的实现类对象
        是通过数据库查询必须要实现的一个业务层接口
 */
@Service
public class UserDetailsServiceImpl extends ServiceImpl<UserMapper, User> implements UserDetailsService, UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //根据用户名查询用户信息
        //数据库中存储的就是通过BCrypt方式加密的密码
        User user = userMapper.selectOne(
                new LambdaQueryWrapper<User>()
                        .eq(StringUtils.isNotBlank(username), User::getUsername, username)
        );

        if(!ObjectUtils.isEmpty(user)){

            //查询用户的权限信息
            /*
                根据用户id，查询user_role表得到roleIds列表
                再根据roleIds的列表数据，查询权限信息
             */
            //List<Map<String,Object>> permissionList = userMapper.selectPermissionByUserId(user.getUserid());
            //List<Permission> permissionList = userMapper.selectPermissionByUserId(user.getUserid());
            List<String> perCodeList = userMapper.selectPercodeByUserId(user.getUserid());

            //封装权限信息
            user.setPerCodeList(perCodeList);

            //让Security权限框架来校验
            return user;
        }

        //用户不存在、用户名密码错误
        return null;
    }
}
